package com.example.component.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import android.view.animation.DecelerateInterpolator
import kotlin.math.cos
import kotlin.math.sin

class LuckyWheelView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : View(context, attrs) {

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.WHITE
        textSize = 40f
        textAlign = Paint.Align.CENTER
    }

    private var startAngle = 0f
    private val itemCount = 6
    private val sectorColors = listOf(
        Color.RED, Color.BLUE, Color.GREEN,
        Color.YELLOW, Color.MAGENTA, Color.CYAN
    )
    private val labels = listOf("一等奖", "二等奖", "三等奖", "四等奖", "谢谢参与", "特等奖")

    fun startSpin(targetIndex: Int) {
        val perAngle = 360f / itemCount
        val targetAngle = 360 * 5 + (itemCount - targetIndex) * perAngle + perAngle / 2

        val animator = ValueAnimator.ofFloat(0f, targetAngle).apply {
            duration = 3000
            interpolator = DecelerateInterpolator()
            addUpdateListener {
                startAngle = it.animatedValue as Float
                invalidate()
            }
        }
        animator.start()
    }


    val radius = width.coerceAtMost(height) / 2f - 20
    val rect = RectF(
        width / 2f - radius, height / 2f - radius,
        width / 2f + radius, height / 2f + radius
    )

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val perAngle = 360f / itemCount
        for (i in 0 until itemCount) {
            paint.color = sectorColors[i % sectorColors.size]
            canvas.drawArc(rect, startAngle + i * perAngle, perAngle, true, paint)

            // 绘制文字
            val angle = Math.toRadians((startAngle + i * perAngle + perAngle / 2).toDouble())
            val textX = (width / 2 + cos(angle) * radius * 0.6).toFloat()
            val textY = (height / 2 + sin(angle) * radius * 0.6).toFloat()
            canvas.drawText(labels[i], textX, textY, textPaint)
        }

        // 可选：绘制中心圆
//        paint.color = Color.WHITE
        paint.color = Color.BLACK
        canvas.drawCircle(width / 2f, height / 2f, 40f, paint)
    }
}
